<?php

namespace app\admin\controller\kuyou;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 计件工资
 *
 * @icon fa fa-circle-o
 */
class Wages extends Backend
{
    /**
     * Procedure模型对象
     * @var \app\admin\model\kuyou\Acceptance
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuyou\Acceptance;
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set', $setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);
    }

    /**
     * 查看
     */
    public function index($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where = [];
            $map = [];
            $searchdata = json_decode(input('filter'), true);
            if ($searchdata) {
                foreach ($searchdata as $k => &$v) {
                    if (!empty($v)) {
                        if ($k == 'id') {
                            $where['ka.' . $k] = ['<', $v];
                        } else if (strpos($v, ' - ') !== false && strpos($k, 'time') !== false) {
                            $str = explode(' - ', $v);
                            $where['ka.' . $k] = ["BETWEEN", [strtotime($str[0]), strtotime($str[1])]];
                        } else {
                            if ($k == 'work_id') {
                                $where['kp.' . $k] = $v;
                            } else {
                                $where['ka.' . $k] = ["LIKE", "%{$v}%"];
                            }
                        }
                    }
                }
            }
            $limit = $this->request->get("limit/d", 999999);
            //新增自动计算页码
            $page = $limit ? intval($offset / $limit) + 1 : 1;
            if ($this->request->has("page")) {
                $page = $this->request->get("page/d", 1);
            }

            $list = Db::name('kuyou_acceptance')->alias('ka')
                ->join('kuyou_production kp', 'ka.production_code=kp.purchase_code')
                ->where('ka.shop_id', $this->shop_id)
                ->where(['ka.code_type' => '1', 'ka.examine_status' => '1'])
                ->where($where)
                ->field('ka.purchase_code as purchase_codes,ka.id as ids,kp.*')
                ->page($page, $limit)->select();
            $count = Db::name('kuyou_acceptance')->alias('ka')
                ->join('kuyou_production kp', 'ka.production_code=kp.purchase_code')
                ->where('ka.shop_id', $this->shop_id)
                ->where(['ka.code_type' => '1', 'ka.examine_status' => '1'])
                ->where($where)
                ->count('kp.id');

            foreach ($list as $list_k => $list_v) {
                $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where('shop_id', $this->shop_id)->where(['id' => $list_v['workshop_id']])->column('name');
                $goods_list = Db::name('kuyou_production_info')->where('shop_id', $this->shop_id)->where(['production_id' => $list_v['id'], 'type' => 2])->field('goods_name,number')->select();
                $str = '';
                foreach ($goods_list as $goods_list_k => $goods_list_v) {
                    $str .= $goods_list_v['goods_name'] . '*' . $goods_list_v['number'] . ' ';
                }
                $list[$list_k]['goods_info'] = $str;

                $list[$list_k]['staff_member'] = Db::name('kuyou_staff_member')->where('shop_id', $this->shop_id)->where(['id' => $list_v['work_id']])->field('men_code,name')->find();

                $hour_free = 0;
                $wages_free = 0;
                $production_id = Db::name('kuyou_plan')->where('shop_id', $this->shop_id)->where(['purchase_code' => $list_v['plan_code']])->value('id');
                $goods_list = Db::name('kuyou_plan_info')->where('shop_id', $this->shop_id)->where(['plan_id' => $production_id])->field('goods_name,number,goods_code')->select();
                $acceptance_list = Db::name('kuyou_acceptance_info')->where('shop_id', $this->shop_id)->where(['production_id' => $list_v['ids']])->column('number', 'goods_code');
                foreach ($goods_list as $goods_list_k => $goods_list_v) {
                    $bom_id = Db::name('kuyou_bom')->where('shop_id', $this->shop_id)->where(['goods_code' => $goods_list_v['goods_code']])->value('id');
                    $procedure = Db::name('kuyou_bom_procedure')->where('shop_id', $this->shop_id)->where(['bom_id' => $bom_id])->select();
                    $this_wages = Db::name('kuyou_bom')->where('shop_id', $this->shop_id)->where(['goods_code' => $goods_list_v['goods_code']])->value('wages');
                    if (isset($acceptance_list[$goods_list_v['goods_code']])) {
                        $wages_free += $this_wages * $acceptance_list[$goods_list_v['goods_code']];
                        foreach ($procedure as $procedure_k => $procedure_v) {
                            $hour_free += ($procedure_v['wages'] * $procedure_v['hours']) * $acceptance_list[$goods_list_v['goods_code']];
                        }
                    }
                }
                $list[$list_k]['hour_free'] = $hour_free;
                $list[$list_k]['wages_free'] = $wages_free;
            }

            $result = array("total" => $count, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $examine = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if (!isset($status)) {
                    $this->error('请填写详情数据');
                }

                //获取设置
                $set = \think\Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->field('type,name,value,is_checked,set')->select();
                $setList = [];
                foreach ($set as $set_k => $set_v) {
                    if (!empty($set_v['set'])) {
                        $set_v['set'] = unserialize($set_v['set']);
                    }
                    $setList[$set_v['name']] = $set_v;
                }
                //数量价格格式化
                $number_decimal = $setList['number_decimal']['value'];

                $number = 0;
                $all_money = 0;
                $data = [];

                $plan = Db::name('kuyou_plan')->where('shop_id', $this->shop_id)->where(['purchase_code' => $params['plan_code']])->find();
                if ($plan) {
                    $info = Db::name('kuyou_plan_info')->where('shop_id', $this->shop_id)->where(['plan_id' => $plan['id']])->select();
                    foreach ($info as $info_k => $info_v) {
                        $number += $info_v['number'];
                        $all_money += $info_v['money'];
                        $data[] = [
                            'shop_id' => $this->shop_id,
                            'type' => 2,
                            'goods_id' => $info_v['goods_id'],
                            'goods_code' => $info_v['goods_code'],
                            'goods_name' => $info_v['goods_name'],
                            'goods_note' => $info_v['goods_note'],
                            'unit_id' => $info_v['unit_id'],
                            'default_unit' => $info_v['default_unit'],
                            'purchase' => $info_v['purchase'],
                            'number' => $info_v['number'],
                            'basic_nmber' => $info_v['basic_nmber'],
                            'money' => $info_v['money'],
                            'stock_number' => 0,
                            'need_number' => $info_v['number'],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                } else {
                    $this->error('生产计划查询失败');
                }

                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $goods = Db::name('kuyou_goods')->where('shop_id', $this->shop_id)->where(['goods_code' => $v])->field('id,goods_code,goods_name')->find();

                        $stock = Db::name('kuyou_goods_stock')->where('shop_id', $this->shop_id)->where(['goods_code' => $v])->sum('stock');
                        if ($stock < $params['basic_nmber'][$k] && $params['number'][$k] != $params['basic_nmber'][$k]) {
                            $goods = Db::name('kuyou_goods')
                                ->where('shop_id', $this->shop_id)
                                ->where(['goods_code' => $v])
                                ->field('goods_type_id,goods_code,goods_name,goods_specification_id,note,unit_id,more_unit,goods_barcode')
                                ->find();;
                            $unit = Db::name('kuyou_unit')->where('shop_id', $this->shop_id)->where((new Goods())->setWhere(['id' => $goods['unit_id']]))->field('id,name')->find();
                            $advance_rate = Db::name('kuyou_unit_conversion')->alias('uc')
                                ->join('kuyou_unit u', 'u.id=uc.vice_unit')
                                ->where('uc.shop_id', $this->shop_id)
                                ->where(['uc.main_unit' => $unit['id'], 'id' => $params['goods_unit'][$k]])
                                ->value('advance_rate');
                            if ($advance_rate) {
                                $stock = round($stock / $advance_rate, $number_decimal);
                            }
                        }

                        $data[] = [
                            'shop_id' => $this->shop_id,
                            'type' => 1,
                            'goods_id' => $goods['id'],
                            'goods_code' => $goods['goods_code'],
                            'goods_name' => $goods['goods_name'],
                            'goods_note' => $params['goods_note'][$k],
                            'unit_id' => (float)$params['goods_unit'][$k],
                            'default_unit' => (float)$params['default_unit'][$k],
                            'purchase' => (float)$params['unit_price'][$k],
                            'number' => (float)$params['number'][$k],
                            'basic_nmber' => (float)$params['basic_nmber'][$k],
                            'money' => (float)$params['all_money'][$k],
                            'stock_number' => $stock,
                            'need_number' => (float)$params['number'][$k],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }
                if (empty($data)) {
                    $this->error('请填写详情数据');
                } else {
                    $admin = Session::get('admin');
                    $row = [
                        'shop_id' => $this->shop_id,
                        'plan_code' => $params['plan_code'],
                        'purchase_code' => $params['purchase_code'],
                        'purchase_time' => strtotime($params['purchase_time']),
                        'work_time' => strtotime($params['work_time']),
                        'finish_time' => strtotime($params['finish_time']),
                        'number' => $number,
                        'all_money' => $all_money,
                        'workshop_id' => $params['workshop_id'],
                        'work_id' => $params['work_id'],
                        'remark' => $params['remark'],
                        'preparation_id' => $admin['id'],
                        'operation_id' => $admin['id'],
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                }

                $result = false;
                Db::startTrans();
                try {
                    if (!empty($row)) {
                        $result = $this->model->insertGetId($row);
                    }

                    foreach ($data as $data_k => $data_v) {
                        $data[$data_k]['production_id'] = $result;
                    }
                    Db::name('kuyou_production_info')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($examine != 1) {
                        try {
                            $exa = $this->examine($result, 1);
                        } catch (Exception $e) {
                        }
                        if (!isset($exa) || $exa['status'] != 1) {
                            $exa = $this->examine($result, 1);
                            try {
                                $this->del($result);
                            } catch (Exception $e) {
                            }
                            $this->error($exa['msg']);
                        }
                    }
                    $this->success('添加成功');
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $code = (new Goods())->getCodes('', 32);
        $this->view->assign("code", $code);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $examine = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
                if ($row['examine_status'] == 1 && $examine == 1) {
                    $this->error('不能编辑已审核的数据');
                }
                $purchase_id = Db::name('kuyou_picking')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能编辑已生成领料单的数据');
                }
                $purchase_id = Db::name('kuyou_material')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能编辑已生成退料单的数据');
                }
                $purchase_id = Db::name('kuyou_acceptance')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能编辑已生成验收单的数据');
                }

                $params = $this->preExcludeFields($params);
                $examine = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if (!isset($status)) {
                    $this->error('请填写详情数据');
                }

                //获取设置
                $set = \think\Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->field('type,name,value,is_checked,set')->select();
                $setList = [];
                foreach ($set as $set_k => $set_v) {
                    if (!empty($set_v['set'])) {
                        $set_v['set'] = unserialize($set_v['set']);
                    }
                    $setList[$set_v['name']] = $set_v;
                }
                //数量价格格式化
                $number_decimal = $setList['number_decimal']['value'];

                $number = 0;
                $all_money = 0;
                $data = [];

                $plan = Db::name('kuyou_plan')->where('shop_id', $this->shop_id)->where(['purchase_code' => $params['plan_code']])->find();
                if ($plan) {
                    $info = Db::name('kuyou_plan_info')->where('shop_id', $this->shop_id)->where(['plan_id' => $plan['id']])->select();
                    foreach ($info as $info_k => $info_v) {
                        $number += $info_v['number'];
                        $all_money += $info_v['money'];
                        $data[] = [
                            'shop_id' => $this->shop_id,
                            'type' => 2,
                            'goods_id' => $info_v['goods_id'],
                            'goods_code' => $info_v['goods_code'],
                            'goods_name' => $info_v['goods_name'],
                            'goods_note' => $info_v['goods_note'],
                            'unit_id' => $info_v['unit_id'],
                            'default_unit' => $info_v['default_unit'],
                            'purchase' => $info_v['purchase'],
                            'number' => $info_v['number'],
                            'basic_nmber' => $info_v['basic_nmber'],
                            'money' => $info_v['money'],
                            'stock_number' => 0,
                            'need_number' => $info_v['number'],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                } else {
                    $this->error('生产计划查询失败');
                }

                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $goods = Db::name('kuyou_goods')->where('shop_id', $this->shop_id)->where(['goods_code' => $v])->field('id,goods_code,goods_name')->find();

                        $stock = Db::name('kuyou_goods_stock')->where('shop_id', $this->shop_id)->where(['goods_code' => $v])->sum('stock');
                        if ($stock < $params['basic_nmber'][$k] && $params['number'][$k] != $params['basic_nmber'][$k]) {
                            $goods = Db::name('kuyou_goods')
                                ->where('shop_id', $this->shop_id)
                                ->where(['goods_code' => $v])
                                ->field('goods_type_id,goods_code,goods_name,goods_specification_id,note,unit_id,more_unit,goods_barcode')
                                ->find();;
                            $unit = Db::name('kuyou_unit')->where('shop_id', $this->shop_id)->where((new Goods())->setWhere(['id' => $goods['unit_id']]))->field('id,name')->find();
                            $advance_rate = Db::name('kuyou_unit_conversion')->alias('uc')
                                ->join('kuyou_unit u', 'u.id=uc.vice_unit')
                                ->where('uc.shop_id', $this->shop_id)
                                ->where(['uc.main_unit' => $unit['id'], 'id' => $params['goods_unit'][$k]])
                                ->value('advance_rate');
                            if ($advance_rate) {
                                $stock = round($stock / $advance_rate, $number_decimal);
                            }
                        }

                        $data[] = [
                            'shop_id' => $this->shop_id,
                            'type' => 1,
                            'goods_id' => $goods['id'],
                            'goods_code' => $goods['goods_code'],
                            'goods_name' => $goods['goods_name'],
                            'goods_note' => $params['goods_note'][$k],
                            'unit_id' => (float)$params['goods_unit'][$k],
                            'default_unit' => (float)$params['default_unit'][$k],
                            'purchase' => (float)$params['unit_price'][$k],
                            'number' => (float)$params['number'][$k],
                            'basic_nmber' => (float)$params['basic_nmber'][$k],
                            'money' => (float)$params['all_money'][$k],
                            'stock_number' => $stock,
                            'need_number' => (float)$params['number'][$k],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }
                if (empty($data)) {
                    $this->error('请填写详情数据');
                } else {
                    $admin = Session::get('admin');
                    $rowdata = [
                        'shop_id' => $this->shop_id,
                        'plan_code' => $params['plan_code'],
                        'purchase_code' => $params['purchase_code'],
                        'purchase_time' => strtotime($params['purchase_time']),
                        'work_time' => strtotime($params['work_time']),
                        'finish_time' => strtotime($params['finish_time']),
                        'number' => $number,
                        'all_money' => $all_money,
                        'workshop_id' => $params['workshop_id'],
                        'work_id' => $params['work_id'],
                        'remark' => $params['remark'],
                        'preparation_id' => $admin['id'],
                        'operation_id' => $admin['id'],
                        'updatetime' => time(),
                    ];
                }

                $result = false;
                Db::startTrans();
                try {
                    if ($examine != 1 && $row['examine_status'] == 1) {
                        $this->examine($ids, 2);
                    }

                    if (!empty($rowdata)) {
                        $result = $this->model->where(['id' => $row['id']])->update($rowdata);
                    }

                    foreach ($data as $data_k => $data_v) {
                        $data[$data_k]['production_id'] = $row['id'];
                    }
                    Db::name('kuyou_production_info')->where('shop_id', $this->shop_id)->where(['production_id' => $row['id']])->delete();
                    Db::name('kuyou_production_info')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($examine != 1) {
                        try {
                            $exa = $this->examine($ids, 1);
                        } catch (Exception $e) {
                        }
                        if (!isset($exa) || $exa['status'] != 1) {
                            $this->error(__('No rows were inserted'));
                        }
                    }
                    $this->success('编辑成功');
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $purchase_info = Db::name('kuyou_production_info')->where('shop_id', $this->shop_id)->where(['production_id' => $row['id'], 'type' => 1])->select();
        foreach ($purchase_info as $purchase_info_k => $purchase_info_v) {
            $purchase_info[$purchase_info_k]['unit'] = json_decode((new GoodsPurchase())->getUnit($purchase_info_v['goods_code']), true);
        }
        $this->view->assign("purchase_info", $purchase_info);

        $this->view->assign("row", $row);

        //审核禁止输入
        $examine_set = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
        if ($examine_set == 1 && $row['examine_status'] == 1) {
            $this->assign('exclass', 'hiddens');
        }
        $this->assignconfig("examine_status", $row['examine_status']);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where('shop_id', $this->shop_id)->where($pk, 'in', $ids)->select();

            foreach ($list as $k => $row) {
                $purchase_id = Db::name('kuyou_picking')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能操作已生成领料单的数据');
                }
                $purchase_id = Db::name('kuyou_material')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能操作已生成退料单的数据');
                }
                $purchase_id = Db::name('kuyou_acceptance')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能操作已生成验收单的数据');
                }
            }

            $examine = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status'] == 1 && $examine == 1) {
                        exception('不能删除已审核的数据');
                        return;
                    } elseif ($v['examine_status'] == 1 && $examine != 1) {
                        try {
                            $this->examine($v['id'], 2);
                        } catch (Exception $e) {
                        }
                    }

                    $count += $v->delete();
                    Db::name('kuyou_production_info')->where('shop_id', $this->shop_id)->where(['production_id' => $v['id']])->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //审核/反审核
    public function examine($ids = null, $examine = 1)
    {
        $examine_set = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
        if (empty($ids)) {
            if ($examine_set != 1) {
                return ['status' => 0, 'msg' => '系统错误'];
            }
            $this->error('请选择要操作的数据');
        }
        $admin = Session::get('admin');
        if ($examine == 1) {
            $list = $this->model->where(['id' => ['in', $ids], 'examine_status' => '0'])->select();
            Db::startTrans();
            try {
                $result = $this->model->where(['id' => ['in', $ids], 'examine_status' => '0'])
                    ->update(['examine_status' => 1, 'examine_id' => $admin['id'], 'examine_time' => time(), 'operation_id' => $admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (isset($result) && $result !== false) {
                if ($examine_set != 1) {
                    return ['status' => 1, 'msg' => '操作成功'];
                }
                $this->success(sizeof($list) . '条数据审核成功');
            } else {
                if ($examine_set != 1) {
                    return ['status' => 0, 'msg' => '操作失败'];
                }
                $this->error('审核失败');
            }
        } else {
            $list = $this->model->where(['id' => ['in', $ids], 'examine_status' => '1'])->select();

            foreach ($list as $k => $row) {
                $purchase_id = Db::name('kuyou_picking')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能操作已生成领料单的数据');
                }
                $purchase_id = Db::name('kuyou_material')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能操作已生成退料单的数据');
                }
                $purchase_id = Db::name('kuyou_acceptance')->where('shop_id', $this->shop_id)->where(['production_code' => $row['purchase_code']])->column('id');
                if (!empty($purchase_id)) {
                    $this->error('不能操作已生成验收单的数据');
                }
            }

            if (empty($list)) {
                if ($examine_set != 1) {
                    return ['status' => 0, 'msg' => '操作失败'];
                }
                $this->error('请选择需要反审核的数据');
            }
            foreach ($list as $list_k => $list_v) {
                $order = Db::name('kuyou_picking')->where('shop_id', $this->shop_id)->where(['production_code' => $list_v['purchase_code']])->column('id');
                if (!empty($order)) {
                    if ($examine_set != 1) {
                        return ['status' => 0, 'msg' => '不能操作已生成领料单的数据'];
                    }
                    $this->error('不能反审核已生成领料单的数据');
                }
                $order = Db::name('kuyou_acceptance')->where('shop_id', $this->shop_id)->where(['production_code' => $list_v['purchase_code']])->column('id');
                if (!empty($order)) {
                    if ($examine_set != 1) {
                        return ['status' => 0, 'msg' => '不能操作已生成验收单的数据'];
                    }
                    $this->error('不能反审核已生成验收单的数据');
                }
            }
            $admin = Session::get('admin');
            Db::startTrans();
            try {
                $result = $this->model->where(['id' => ['in', $ids], 'examine_status' => '1'])
                    ->update(['examine_status' => '0', 'examine_id' => 0, 'examine_time' => '', 'operation_id' => $admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (isset($result) && $result !== false) {
                if ($examine_set != 1) {
                    return ['status' => 1, 'msg' => '操作成功'];
                }
                $this->success(sizeof($list) . '条数据反审核成功');
            } else {
                if ($examine_set != 1) {
                    return ['status' => 0, 'msg' => '操作失败'];
                }
                $this->error('反审核失败');
            }
        }
    }

    public function choselist()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $data = input();
            if (isset($data['purchase_code'])) {
                $detail = Db::name('kuyou_production')->where('shop_id', $this->shop_id)->where(['purchase_code' => $data['purchase_code']])->find();
                if ($detail) {
                    $info = Db::name('kuyou_production_info')->where('shop_id', $this->shop_id)->where(['production_id' => $detail['id']])->select();
                    foreach ($info as $info_k => $info_v) {
                        $info[$info_k]['unit'] = Db::name('kuyou_unit')->where('shop_id', $this->shop_id)->where(['id' => $info_v['unit_id']])->find();
                    }
                } else {
                    $info = [];
                }
                $result = array("total" => sizeof($info), "rows" => $info);
                return json($result);
            } else {
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();

                $list = $this->model
                    ->where('acceptance.shop_id', $this->shop_id)
                    ->where($where)
                    ->where(['examine_status' => '1'])
                    ->order($sort, $order)
                    ->paginate($limit);

                foreach ($list as $list_k => $list_v) {
                    $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where(['id' => $list_v['workshop_id']])->column('name');
                    $goods_list = Db::name('kuyou_production_info')->where('shop_id', $this->shop_id)->where(['production_id' => $list_v['id'], 'type' => 2])->field('goods_name,number')->select();
                    $str = '';
                    foreach ($goods_list as $goods_list_k => $goods_list_v) {
                        $str .= $goods_list_v['goods_name'] . '*' . $goods_list_v['number'] . ' ';
                    }
                    $list[$list_k]['goods_info'] = $str;
                }

                $result = array("total" => $list->total(), "rows" => $list->items());
                return json($result);
            }
        }
        return $this->view->fetch();
    }

    public function planinfo()
    {
        $params = input();
        $plan = Db::name('kuyou_plan')->where('shop_id', $this->shop_id)->where(['purchase_code' => $params['purchase_code']])->find();
        if ($plan) {
            $info = Db::name('kuyou_plan_info')->where('shop_id', $this->shop_id)->where(['plan_id' => $plan['id']])->select();
            $data = [];
            foreach ($info as $info_k => $info_v) {
                $bom = Db::name('kuyou_bom')->where('shop_id', $this->shop_id)->where(['goods_code' => $info_v['goods_code']])->column('id');
                $info_id = Db::name('kuyou_bom_info')->where('shop_id', $this->shop_id)->where(['bom_id' => ['in', $bom]])->select();
                foreach ($info_id as $info_id_k => $info_id_v) {
                    $info_id_v['number'] = $info_id_v['number'] * $info_v['number'];
                    $info_id_v['basic_nmber'] = $info_id_v['basic_nmber'] * $info_v['number'];
                    $info_id_v['money'] = $info_id_v['money'] * $info_v['number'];
                    $data[] = $info_id_v;
                }
            }
            $result = array("total" => sizeof($data), "rows" => $data);
            return json($result);
        } else {
            $this->error('查询失败');
        }
    }

}
